package com.ti.winona.ui;

import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.image.SmartImageView;
import com.taplinker.client.App;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.R;
import com.taplinker.client.core.LocalFileManager;
import com.taplinker.client.domain.UserInfo;
import com.taplinker.client.im.SocketTemplateContext;
import com.taplinker.client.im.rpc.Cmd002;
import com.taplinker.core.rpc.RpcClientContext;
import com.taplinker.core.util.Base64;
import com.taplinker.core.util.DeviceUtil;
import com.taplinker.core.util.json.JsonUtil;
import com.ti.winona.ConstantValue;
import com.ti.winona.net.API;
import com.ti.winona.net.RequestClient;
import com.ti.winona.util.IPUtil;
import com.ti.winona.util.QuitOperateUtil;
import com.ti.winona.util.SharedPreferencesUtil;
import com.ti.winona.widget.LoadingDialog;
import com.ti.winona.bean.User;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {

	private View mView;
	private EditText mEditTxtAccount;
	private EditText mEditTxtPwd;
	private EditText mEditTxtVerify;
	private Button mBtnCommitLogin;
	private SmartImageView mImgVerify;
	
	private LoadingDialog mLoadingDialog;
	
	private String mCodeToken;
	
	private String mUserName;
	private String mPassword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		IPUtil.initIP(); // 初始化IP
		findView();
		init();
		initDialog();
		loadVerifyImage();
		initListener();
	}
	
	private void findView() {
		mView = (View) findViewById(R.id.lin_login);
		mEditTxtAccount = (EditText) findViewById(R.id.edt_txt_username);
		mEditTxtPwd = (EditText) findViewById(R.id.edt_txt_password);
		mEditTxtVerify = (EditText) findViewById(R.id.edt_txt_verify);
		mBtnCommitLogin = (Button) findViewById(R.id.btn_login);
		mImgVerify = (SmartImageView) findViewById(R.id.img_smart_verify);
	}
	
	private void init() {
		mUserName = SharedPreferencesUtil.getString(this, ConstantValue.sharedpreferences.SHARED_NAME, ConstantValue.sharedpreferences.USER_NAME);
		mPassword = SharedPreferencesUtil.getString(this, ConstantValue.sharedpreferences.SHARED_NAME, ConstantValue.sharedpreferences.USER_PASSWORD);
		
		if(mUserName!=null && !"".equals(mUserName) && mPassword!=null && !"".equals(mPassword)) {
			mEditTxtAccount.setText(mUserName);
			mEditTxtPwd.setText(mPassword);
		}
	}
	
	// 获取验证码Image
	private void loadVerifyImage() {
		mEditTxtVerify.setText(""); // 清空输入框
		RequestClient.get(this, API.VERFIY_IMAGE, new AsyncHttpResponseHandler(){
			
			@Override
			public void onStart() {
				super.onStart();
				mLoadingDialog.setText("读取验证码");
				mLoadingDialog.show();
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				try {
					JSONObject jsonObject = new JSONObject(content);
					if("OK".equalsIgnoreCase(jsonObject.getString("code"))) {
						
						JSONObject body = jsonObject.getJSONObject("body");
						byte[] bts = Base64.decode(body.getString("image"));
						Bitmap bmp = BitmapFactory.decodeByteArray(bts, 0, bts.length);
						mImgVerify.setImageBitmap(bmp);
						
						mCodeToken = body.getString("key");
					}else{
						onFailure(null, "验证码code不为OK");
					}
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(null, "验证码获取解析出错");
				}
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				App.showLog("log_ktian", "http-login_LoginActivity-Failure");
				App.showToast("获取验证码失败， 请点击验证码刷新!");
			}

			@Override
			public void onFinish() {
				super.onFinish();
				mLoadingDialog.dismiss();
			}

		});
	}
	
	private void initListener() {
		// 整个View设置监听, 隐藏软件盘
		mView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				hideKeyboard();
			}
		});
		// 登陆监听
		mBtnCommitLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkInput()) {
					httpLogin();
				}else{
					// 刷新验证码
					loadVerifyImage();
				}
			}
		});
		// 验证码获取监听
		mImgVerify.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				loadVerifyImage();
			}
		});
		
	}
	
	private boolean checkInput() {
		String username = mEditTxtAccount.getText().toString().trim();
		String password = mEditTxtPwd.getText().toString().trim();
		String code = mEditTxtVerify.getText().toString().trim();
		
		if (!DeviceUtil.isNetworkAvailable(getApplicationContext())) {
			App.showToast("当前网络不可用");
			return false;
		}
		if (TextUtils.isEmpty(username)) {
			App.showToast("请输入邮箱地址");
			return false;
		}
		if (TextUtils.isEmpty(password)) {
			App.showToast("请输入密码");
			return false;
		}
		if (TextUtils.isEmpty(code)) {
			App.showToast("请输入验证码");
			return false;
		}
		return true;
	}
	
	private void initDialog() {
		mLoadingDialog = new LoadingDialog(this);
		mLoadingDialog.setCancelable(true);
		mLoadingDialog.setCanceledOnTouchOutside(false);
	}
	
	private void httpLogin() {
		mUserName = mEditTxtAccount.getText().toString().trim();
		mPassword = mEditTxtPwd.getText().toString().trim();
		final String code = mEditTxtVerify.getText().toString().trim();
		
		RequestParams params = new RequestParams();
		params.put("body.username", mUserName);
		params.put("body.password", mPassword);
		if (!TextUtils.isEmpty(code) && !TextUtils.isEmpty(mCodeToken)) {
			params.put("code", code);
			params.put("codeToken", mCodeToken);
		}
		params.put("from", "EXPERT");
		
		RequestClient.post(this, API.HTTP_LOGIN, params, new AsyncHttpResponseHandler(){

			@Override
			public void onStart() {
				super.onStart();
				mLoadingDialog.setText("正在登录...");
				mLoadingDialog.show();
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				App.showLog("log_ktian", "http-login-Failure");
				mLoadingDialog.dismiss();
				loadVerifyImage(); // 更新验证码
				App.showToast("登录失败, 请重试!");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				App.showLog("log_ktian", "http-login_welcome-Success");
				try {
					JSONObject jsonObject = new JSONObject(content);
					if("OK".equalsIgnoreCase(jsonObject.getString("code"))) {
						
						User user = JsonUtil.jsonToObject(jsonObject.getString("body"), User.class);
						
						UserInfo userInfo = new UserInfo();
						userInfo.setUserName(user.getExpert().getUsername());
						userInfo.setUserIcon(user.getExpert().getHead());
						userInfo.setId(Long.valueOf(user.getExpert().getId()));
						userInfo.setUserid(Long.valueOf(user.getExpert().getUserid()));
						userInfo.setNickname(user.getExpert().getName());
						
						userInfo.setToken(user.getToken());
						userInfo.setImToken(user.getToken());
						
//						Expert expert = new Expert();
//						expert.setHead(user.getExpert().getHead());
//						expert.setPhysicianCertificate(user.getExpert().getPhysicianCertificate());
//						expert.setIdentification(user.getExpert().getIdentification());
//						expert.setPosition(user.getExpert().getPosition());
//						expert.setPhone(user.getExpert().getPhone());
//						expert.setMail(user.getExpert().getMail());
//						expert.setSexual(user.getExpert().getSexual());
//						expert.setId(user.getExpert().getId());

						AppConfigFactory.getInstance().setAppKey("19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7");
						AppConfigFactory.getInstance().setUserInfo(userInfo);
						AppConfigFactory.getInstance().setUser(user);
						
						LocalFileManager.getInstance().ayscCreateDirs();
						RpcClientContext.getInstance().setCookies("TAPLINKER_TOKEN=" + user.getToken());
						SocketTemplateContext.getInstance().initialize(LoginActivity.this);
						
						// 登录成功, 记录用户名和密码
						saveUserAndPwd();
						
						// 开始Taplinker登陆
						new Cmd002(LoginActivity.this, mLoadingDialog).execute();
						
					}else{
						App.showToast(jsonObject.getString("message"));
						onFailure(null, "http登录code为FAILED");
					}
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(null, "http登陆解析出错");
				}
				
			}
			
		});
	}
	
	private void saveUserAndPwd() {
		SharedPreferencesUtil.putString(this, ConstantValue.sharedpreferences.SHARED_NAME, 
				ConstantValue.sharedpreferences.USER_NAME, mUserName);
		SharedPreferencesUtil.putString(this, ConstantValue.sharedpreferences.SHARED_NAME, 
				ConstantValue.sharedpreferences.USER_PASSWORD, mPassword);
	}
	
	/**
	 * 隐藏输入法面板
	 */
	protected void hideKeyboard() {
		InputMethodManager imm = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
		if (imm != null && getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	
	@Override
	public void onBackPressed() {
		// 连续点击两次退出程序
		QuitOperateUtil.quitProgram(LoginActivity.this);
	}
	
}
